package com.dingpeikeji.quickdeer.modules.wx.base.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.isouland.cpwx.api.base.WxOAuthAPI;
import org.isouland.cpwx.api.core.util.HttpUtil;
import org.isouland.cpwx.api.core.util.SingleAccessToken;
import org.isouland.cpwx.api.user.WxUserAPI;
import org.isouland.cpwx.api.user.req.WxUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;
import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.count.entity.CountInfo;
import com.dingpeikeji.quickdeer.core.modules.count.service.TCountService;
import com.dingpeikeji.quickdeer.core.modules.driver.entity.TDrivers;
import com.dingpeikeji.quickdeer.core.modules.driver.service.TDriversService;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.site.entity.TSitedtl;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Area;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Role;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.SysAds;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.core.modules.sys.service.SysAdsService;
import com.dingpeikeji.quickdeer.core.modules.sys.service.SystemService;
import com.dingpeikeji.quickdeer.mobile.service.TravelProductService;
import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;
import com.dingpeikeji.quickdeer.modules.interceptor.FrontBaseInterceptor;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.DemandsReact;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TDemands;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentgroup;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FDemandsService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FRentproductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductOrderService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TCargotypeService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentgroupService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentproductService;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.dingpeikeji.quickdeer.modules.wx.common.web.OAuth;
import com.dingpeikeji.quickdeer.modules.wx.interceptor.OAuthInterceptor;
import com.dingpeikeji.quickdeer.modules.wx.member.service.WxMemberService;
import com.dingpeikeji.quickdeer.utils.BackResult;
import com.dingpeikeji.quickdeer.utils.JedisClient;
import com.dingpeikeji.quickdeer.utils.StringUtil;
import com.google.common.collect.Lists;
import com.tencent.common.Configure;

/**
 * 微信端通用页面
 */
@Controller
@RequestMapping("${wxPath}/pu")
public class WxCommonController extends BaseController{
	@Autowired
	private SysAdsService sysAdsService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private FrontUserService userService;
	@Autowired
	private TCountService tCountService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private FRentproductService rentproductService;
	@Autowired
	private WxMemberService memberService;
	@Autowired
	private TSitedtlService tSitedtlService;
	@Autowired
	private TRentgroupService tRentgroupService;
	public static final String FRONT_USER_IN_SESSION = "front_user";
	public static String frontPath = "/wx";
	@Autowired
	private JedisClient jedisClient;

	@RequestMapping("index")
	public String index(Model model,String code,String state,HttpServletRequest request) {
		String openid = "";
		List<SysAds> sysAds = sysAdsService.getBannerImage();
		if (sysAds!=null && sysAds.size()>0) {
			for (int i = 0; i < sysAds.size(); i++) {
				model.addAttribute("sysAds"+i, sysAds.get(i).getPageurl());
			}
		}
		model.addAttribute("navStyle", "indexPage");
		if (StringUtils.isNotEmpty(code)) {
			openid = WxOAuthAPI.getOpenid(Configure.getAppid(), Configure.getAppsecret(), code);
		}
		if(!StringUtils.isEmpty(openid) && (state.equals("pu"))) {
			logger.debug("普通用户访问");
			User commonUser = (User)request.getSession().getAttribute(OAuth.FRONT_USER_IN_SESSION);
			if (commonUser == null){
				// 身份认证
				User query = new User();
				query.setWechatId(openid);
				List<User> userList = memberService.findList(query);
				if(userList!=null && !userList.isEmpty()){ // 认证通过
					request.getSession().setAttribute(OAuth.FRONT_USER_IN_SESSION, userList.get(0));
				}
			}
			return "redirect:"+Global.getWxPath()+"/pu/index";
		}
		return "wx/modules/base/index";
	}
	public static void defaultTime(Model model, HttpServletRequest request) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_YEAR, +1);
		model.addAttribute("defaultTime", sdf.format(calendar.getTime())+" 09:00");
	}
	@RequestMapping("checkTime")
	public void checkTime(HttpServletRequest request,HttpServletResponse response,String time,String endtime) throws IOException, ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date userTime = sdf.parse(time);
		Long fromdateLong = userTime.getTime() - 60*60*1000*2;
		//3个月之后不能选
		Calendar fromdateCal = Calendar.getInstance();
		fromdateCal.setTime(sdf.parse(time));
		Calendar threeMonthCal = Calendar.getInstance();
		threeMonthCal.add(Calendar.MONTH, +3);
		if (StringUtils.isNotEmpty(endtime)) {
			Date endTime = sdf.parse(endtime);
			Long fromdateLong2 = endTime.getTime() - 60*60*1000*2;
			if(userTime.before(endTime)){
				response.getWriter().println("3");
				return;
			}else if (new Date(fromdateLong2).before(new Date())) {
				response.getWriter().println("4");
				return;
			}
		}
		if(new Date(fromdateLong).before(new Date())){
			//return "距离发车时间不足2小时，请重新选择发车时间";
			response.getWriter().println("1");
			return;
		}else if (fromdateCal.getTime().after(threeMonthCal.getTime())) {
			//超过三个月
			response.getWriter().println("2");
			return;
		}else{
			response.getWriter().println("0");
			return;
		}
	}
	/*@RequestMapping("my")
	public String my(Model model,HttpServletRequest request) {
		User user = (User)request.getSession().getAttribute(OAuth.SESSION_PUBUSER);
		model.addAttribute("user", user);
		// 获取微信头像
		String headImgUrl = "";
		// 因为调试的时候没有微信身份则使用模拟方式
		Boolean isDebug = (Boolean)request.getSession().getAttribute(OAuth.SESSION_DEBUG);
		if(isDebug==null || !isDebug) {
			String accessToken = SingleAccessToken.getInstance().getAccessToken().getAccesstoken();
			if(user!=null&&StringUtils.isNotEmpty(accessToken)){
				WxUserInfo info = WxUserAPI.getUserInfo(accessToken, user.getWechatId());
				if(info!=null){
					headImgUrl = info.getHeadImgUrl();
				}else{
					// 如果重复获取导致上次获取的accessToken失效重新访问
					SingleAccessToken.clearInstance(); // 清空原来的accessToken
					accessToken = SingleAccessToken.getInstance().getAccessToken().getAccesstoken();
					info = WxUserAPI.getUserInfo(accessToken, user.getWechatId());
					if(info!=null){
						headImgUrl = info.getHeadImgUrl();
					}
				}
			}
		}
		model.addAttribute("headImgUrl",headImgUrl);
		return "wx/modules/base/my";
	}*/
	@RequestMapping(value="login")
	public String doLogin(HttpServletRequest request,RedirectAttributes redirectAttributes, 
			HttpServletResponse response,Model model) throws Exception{
		String password = (String) request.getParameter("password");
		String username = (String) request.getParameter("username");
		String saveUserFor3Months = (String) request.getParameter("saveUserFor3Months");
		User user = (User)request.getSession().getAttribute(FRONT_USER_IN_SESSION);
		// 返回页面，先从地址参数中获取返回路径，如果没有则从session中获取
		String backPage = (String)request.getParameter("backUrl");
		if(StringUtils.isEmpty(backPage)) { // 如果没有任何路径，则直接进入首页
			backPage = frontPath + "/pu/index";
		}
		String message = "";
		if(user != null) {
			return "redirect:"+backPage;
		} else { // 验证用户
				user = new User();
				user.setLoginName(username);
				List<User> userList = userService.findList(user);
				if(userList != null && !userList.isEmpty()) { // 存在用户
					user = userList.get(0);
					user.setOffice(officeService.get(user.getOffice()));
					if(user.getLoginFlag().equals("1") && "1".equals(user.getOffice().getUseable())){
						// 比对密码
						if(SystemService.validatePassword(password, user.getPassword())) {
							user = userList.get(0);
							Office office = officeService.get(user.getOffice()); // 用户所属部门
							user.setOffice(office);
							//int treeMonths = 30*24*60*60;
							if(StringUtils.isNotEmpty(saveUserFor3Months) && saveUserFor3Months.equals("yes")) {
								//勾选了30天自动登录
								Cookie cookie = new Cookie("autoLogin", user.getLoginName()+"#"+user.getPassword());
								cookie.setPath(request.getContextPath());
								cookie.setMaxAge(30* 24 * 60 * 60);
								response.addCookie(cookie);
							} 
							if (backPage.contains("login")&&!backPage.contains("backUrl")) {
								backPage = frontPath + "/pu/index";
								//存到session
								request.getSession().setAttribute(FRONT_USER_IN_SESSION, user);
								return "redirect:"+backPage;
							}else if(backPage.contains("backUrl")){
								String[] arr = backPage.split("backUrl=");
								String str = arr[1];
								//获取微信返回的code和openid
								if (StringUtils.isEmpty(user.getWechatId())) {//已经有openid,就不再获取
									String code = str.split("code=")[1].split("&state=")[0];
									if (StringUtils.isNotBlank(code)) {
										String openid = WxOAuthAPI.getOpenid(Configure.getAppid(), Configure.getAppsecret(), code);
										if(!StringUtils.isEmpty(openid)) {
											//保存openid到user
											userService.saveOpenId(openid,user.getId());
										}
									}
								}
								//存到session
								request.getSession().setAttribute(FRONT_USER_IN_SESSION, user);
								return "redirect:"+str;
							}
						}
						message = "用户名或密码不正确";
					} else {
						message = "该账号已禁用";
					}
				}else{
					message = "用户名不存在";
				}
		}
		request.getSession().setAttribute("mes", message);
		return "redirect:"+backPage;
	}
	@RequestMapping("doregister")
	public String doregister(User user, String validateCode,String code,
			String officeName, RedirectAttributes redirectAttributes, 
			HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		List<String> messages = Lists.newArrayList(); // 消息
		String userType = user.getUserType();
		//单位注册
		if (validateCode==null) {
			validateCode = request.getParameter("validate2");
		}
		if (StringUtils.isEmpty(user.getMobile())) {
			user.setMobile(request.getParameter("mobile2"));
		}
		if (StringUtils.isEmpty(user.getNewPassword())) {
			user.setNewPassword((request.getParameter("confirmNewPassword2")));
		}
		String mobileFromRedisCode = jedisClient.get("registercode: "+user.getMobile());
		if (StringUtil.isEmpty(mobileFromRedisCode)) {
			messages.add("短信验证码超时");
		}
		if (StringUtil.isEmpty(validateCode)) {
			messages.add("短信验证码为空");
		}
		if (!mobileFromRedisCode.equals(validateCode)&&StringUtils.isNotBlank(mobileFromRedisCode)&&StringUtils.isNotBlank(validateCode)) {
			messages.add("短信验证码错误");
		}
		if(!messages.isEmpty()) { // 验证码校验不通过
			request.getSession().setAttribute("mes", messages.get(0));
			return "redirect:"+Global.getWxPath()+"/pu/register";
		} else {
			// 默认个人用户
			Office company = new Office();
			company.setId(Global.getConfig("front.companyid"));//0
			Office office = new Office();
			office.setId(Global.getConfig("front.officeid"));// "-"
			user.setCompany(company);
			user.setOffice(office);
			user.setLoginName(user.getMobile());
			if(ValidateTool.isEmptyOrNull(user.getName())) {
				user.setName(user.getMobile());
			}
			if (!beanValidator(redirectAttributes, user)){
				return "redirect:"+Global.getWxPath()+"/pu/register";
			}
			if("1".equals(userType) && ValidateTool.isEmptyOrNull(officeName)) {
				messages.add("请填写企业名称");
			}
			user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
			if (systemService.getUserByLoginName(user.getLoginName()) != null){
				messages.add("手机号已注册");
			}
		}
		if(messages.isEmpty()) {
			// 角色数据有效性验证，过滤不在授权内的角色
			List<Role> roleList = Lists.newArrayList();
			Role r = new Role();
			r.setId(Global.getConfig("front.roleid"));//2
			
			// 如果是企业注册
			if("1".equals(userType)) {
				r.setId(Global.getConfig("front.e.roleid"));
				// 新建普通单位
				Office office = new Office();
				String cid = UUID.randomUUID().toString().replace("-", "");
				office.setId(cid);
				Office parent = new Office();
				parent.setId(Global.getConfig("front.e.companyid"));
				office.setParent(parent);
				office.setParentIds("0,1,"+parent.getId()+",");
				office.setName(officeName);
				Area area = new Area();
				area.setId("20"); // 区域默认跟平台保持一致
				office.setArea(area);
				office.setType("2");
				office.setUseable("1"); // 可登陆
				office.setDelFlag("0"); // 未删除
				office.setFlatType("5");
				Date date = new Date();
				office.setCreateDate(date);
				office.setUpdateDate(date);
				User admin = new User(); // 操作用户默认都是管理员
				admin.setId("1");
				office.setCreateBy(admin);
				office.setUpdateBy(admin);
				officeService.savef(office); // 保存客运公司
				
				user.setCompany(office);
				user.setOffice(office);
			}
			roleList.add(r);
			user.setRoleList(roleList);
			systemService.savePubUser(user);
			System.out.println("code====="+code);
			//获取微信返回的code和openid
			if (StringUtils.isEmpty(user.getWechatId())) {//已经有openid,就不再获取
				if (StringUtils.isNotBlank(code)) {
					String openid = WxOAuthAPI.getOpenid(Configure.getAppid(), Configure.getAppsecret(), code);
					if(!StringUtils.isEmpty(openid)) {
						//保存openid到user
						userService.saveOpenId(openid,user.getId());
					}
				}
			}
			//统计
			CountInfo countInfo=tCountService.findList(null).get(0);
			int t=countInfo.getHtmlNum()+1;
			countInfo.setHtmlNum(t);
			countInfo.setTotalCount(countInfo.getAndriodNum()+countInfo.getIosNum()+countInfo.getHtmlNum());
			tCountService.update(countInfo);
			return "redirect:/wxlogin.jsp";
		} else {
			request.getSession().setAttribute("mes", messages.get(0));
			return "redirect:"+Global.getWxPath()+"/pu/register";
		}
	}
	@RequestMapping("logout")
	public String logout(HttpServletRequest request,RedirectAttributes redirectAttributes,HttpServletResponse response){
		User user = (User)request.getSession().getAttribute(FRONT_USER_IN_SESSION);
		if(user != null) {
			request.getSession().invalidate();
			// 清空自动登录的Cookie:
			Cookie cookie = new Cookie("autoLogin","");
			cookie.setPath(request.getContextPath());
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
		return "redirect:"+frontPath+"/pu/index";
	}
	@RequestMapping(value = "/forgetPwd")
	public String modifyPwd(String mobile, String password1, String password2,
			String validateCode, HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		List<String> messages = Lists.newArrayList(); // 消息
		String mobileFromRedisCode = jedisClient.get("registercode: "+mobile);
		if (StringUtil.isEmpty(mobileFromRedisCode)) {
			messages.add("短信验证码超时");
		}
		if (!mobileFromRedisCode.equals(validateCode)) {
			messages.add("短信验证码错误");
		}
		if(messages.isEmpty()) {
				User user = new User();
				user.setLoginName(mobile);
				List<User> userList = systemService.findList(user);
				if(userList!=null && !userList.isEmpty()){
					user = userList.get(0);
					systemService.updatePasswordById(user.getId(), user.getLoginName(), password1);
					request.getSession().setAttribute("mes", "密码修改成功,请重新登录");
				} else {
					request.getSession().setAttribute("mes", "手机号未注册");
				}
		}else {
			request.getSession().setAttribute("mes", messages.get(0));
		}
		return "redirect:"+Global.getWxPath()+"/pu/password";
	}
	@RequestMapping("register")
	public String register(HttpServletResponse response,HttpServletRequest request,String code) throws Exception {
		String basePath = new String();
		if (request.getServerPort() == 80) {
			basePath = request.getScheme() + "://"
					+ request.getServerName();
		}else{
			basePath = request.getScheme() + "://"
					+ request.getServerName() + ":" + request.getServerPort();
		}
		if (!basePath.contains("localhost")) {
			response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?"
					+ "appid=wx70cbd1f125e9b16e&redirect_uri="+URLEncoder.encode("https://www.xiakeyueche.com/wxregister.jsp")
					+ "&response_type=code&scope=snsapi_base&state=pu#wechat_redirect");
		}
		return "redirect:/wxregister.jsp";
	}
	@RequestMapping("password")
	public String password() {
		return "wx/modules/base/wxpassword";
	}
	@RequestMapping("wait")
	public String waitPage() {
		return "wx/modules/base/wait";
	}
	
	@RequestMapping("aboutUsPage")
	public String aboutUsPage(Model model) {
		return "wx/modules/base/aboutUs";
	}
	
	@RequestMapping("travelIndex")
	public String travelIndex(TRentproduct tRentproduct, TRentgroup tRentgroup,HttpServletResponse response, 
			HttpServletRequest request,Model model) throws IOException {
		String cityName = TravelProductService.ipLocation(request);
		//根据cityname查询对应的siteid
		String siteid = tSitedtlService.getSiteIdByName(cityName);
		tRentgroup.setTraveltype(1);
		tRentgroup.setDepartcity(tRentproduct.getDepartcity());
		tRentgroup.setSiteid(siteid);
		tRentgroup.setSitename(cityName);
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
		//分页查询
		List<TRentgroup> groupList =tRentgroupService.getMobileTravelProducts(tRentgroup);
		if(groupList.size()==0||groupList==null){
			//按照上海去查询
			tRentgroup.setTraveltype(1);
			tRentgroup.setSiteid(433+"");
			tRentgroup.setSitename("上海市");
			tRentgroup.setIshot(request.getParameter("ishot"));
			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
			groupList =tRentgroupService.getMobileTravelProducts(tRentgroup);
		}
		List<TRentgroup> rentGroupList = new ArrayList<TRentgroup>();
		for (int i = 0; i < 4; i++) {
			rentGroupList.add(groupList.get(i));
		}
		model.addAttribute("rentGroupList", rentGroupList);
		return "wx/modules/travelProduct/travelIndex";
	}
	@RequestMapping("dayIndex")
	public String dayIndex(HttpServletRequest request,Model model) {
		WxCommonController.defaultTime(model, request);
		return "wx/modules/dayProduct/dayIndex";
	}
	@RequestMapping("airIndex")
	public String airIndex(Model model,HttpServletRequest request) {
		WxCommonController.defaultTime(model, request);
		return "wx/modules/airProduct/airIndex";
	}
	@RequestMapping("tripIndex")
	public String tripIndex(Model model,HttpServletRequest request) {
		WxCommonController.defaultTime(model, request);
		return "wx/modules/tripProduct/tripIndex";
	}
}
